﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BuildStatus.Web.BuildServer
{
    public class BuildSettings
    {
        private static BuildSettings _settings;

        private BuildSettings()
        {
            this.TFSUri = BuildStatus.Web.Properties.Settings.Default.TFSUri;
            this.TFSUsername = BuildStatus.Web.Properties.Settings.Default.TFSUsername;
            this.TFSPassword = BuildStatus.Web.Properties.Settings.Default.TFSPassword;
            this.UseRestAPI = BuildStatus.Web.Properties.Settings.Default.UseRestAPI;
            this.EmbeddedHtmlFile = BuildStatus.Web.Properties.Settings.Default.EmbeddedHtmlFile;
            this.EmbeddedHtmlTitle = BuildStatus.Web.Properties.Settings.Default.EmbeddedHtmlTitle;

            if (string.IsNullOrEmpty(this.TFSUri) || this.TFSUri.IndexOf("xyz.visualstudio.com", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                try
                {
                    using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\BuildStatus"))
                    {
                        this.TFSUri = (string)key.GetValue("TFSUri");
                        this.TFSUsername = (string)key.GetValue("TFSUsername");
                        this.TFSPassword = (string)key.GetValue("TFSPassword");
                        this.UseRestAPI = ((int)key.GetValue("UseRestAPI", 0) > 0);
                        this.EmbeddedHtmlFile = (string)key.GetValue("EmbeddedHtmlFile");
                        this.EmbeddedHtmlTitle = (string)key.GetValue("EmbeddedHtmlTitle");
                    }
                }
                catch
                {
                }
            }
        }

        public static BuildSettings Settings
        {
            get
            {
                if (_settings == null || string.IsNullOrEmpty(_settings.TFSUri))
                    _settings = new BuildSettings();

                return _settings;
            }
        }

        public string TFSUri { get; private set; }
        public string TFSUsername { get; private set; }
        public string TFSPassword { get; private set; }
        public bool UseRestAPI { get; private set; }
        public string EmbeddedHtmlFile { get; private set; }
        public string EmbeddedHtmlTitle { get; private set; }
    }
}